#pragma once
#include<iostream>
#include<sys/epoll.h>
#include<sys/types.h>
#include"log.hpp"
#include<map>
#include <unistd.h>

//封装epoller
class Epoller{
    public:
        Epoller():_epoll_fd(epoll_create(1024)){//创建epoll句柄，最大监听数为1024
            if(_epoll_fd==-1){
                LOG(ly::LogLevel::ERROR)<<"创建epoll句柄失败"<<"\n";
                exit(1);
            }
        }
        ~Epoller(){
            close(_epoll_fd);
        }
        bool AddChannel(int fd,epoll_event* event){//添加监听事件
            //_channels[fd]=channel;
            int n=epoll_ctl(_epoll_fd,EPOLL_CTL_ADD,fd,event);
            if(n==-1){
                LOG(ly::LogLevel::ERROR)<<"添加epoll事件失败"<<"\n";
                return false;
            }
            return true;
        }
        bool DelChannel(int fd){
            int n=epoll_ctl(_epoll_fd,EPOLL_CTL_DEL,fd,0);
            if(n==-1){
                LOG(ly::LogLevel::ERROR)<<"删除epoll事件失败"<<"\n";
                return false;
            }
            n=close(fd);
            if(n==-1){
                LOG(ly::LogLevel::ERROR)<<"关闭fd失败"<<"\n";
                return false;
            }
            LOG(ly::LogLevel::INFO)<<"删除监听事件成功"<<fd<<"\n";
            return true;
        }
        bool ModChannel(int fd,epoll_event* event){
            int n=epoll_ctl(_epoll_fd,EPOLL_CTL_MOD,fd,event);
            if(n==-1){
                LOG(ly::LogLevel::ERROR)<<"修改epoll事件失败"<<"\n";
                return false;
            }
            return true;
        }
        int GetFd(){
            return _epoll_fd;
        }
    private:
        //std::map<int,Channel*> _connections;
        int _epoll_fd;
};